/*
 * @Author: wcx 1055127249@qq.com
 * @Date: 2025-01-13 15:22:27
 * @LastEditors: wcx 1055127249@qq.com
 * @LastEditTime: 2025-01-14 10:56:06
 * @FilePath: \my-project\src\views\CreateProcess\GraphProcess.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import './node/event'
import './node/gateway'
import './node/activity'
import { Graph } from '@antv/x6'

export class GraphProcess extends Graph {
  constructor(options) {
    super(options)
  }
  addTask(data) {
    const { label = '', error = '', ...obj } = data
    this.addNode({
      ...obj,
      attrs: {
        label: { text: label },
        error: { text: error }
      }
    })
  }

  setTaskNode(node, data){
    node.setData(data)
    node.attr('label/text', data.label)
  }

  validate() {
    const result = true
    const nodes = this.getNodes();
    const { cells } = this.toJSON();
    const ends = nodes.filter(i => i.shape === 'end')
    const starts = nodes.filter(i => i.shape === 'start')
    console.log(ends,starts)
    if (!starts.length && !ends.length) {
      return Promise.reject(new Error('流程缺少开始节点或结束节点'))
    }
    nodes.forEach(node => {
      const srcrce = cells.filter(i => i?.source?.cell === node.id)
      const target = cells.filter(i => i?.target?.cell === node.id)
      console.log(node, srcrce, target)
      if (node.shape === 'start' && target.length) {
        node.attr('error/text', '开始节点连接有误')
        result = false
      }
      if (node.shape === 'end' && srcrce.length) {
        node.attr('error/text', '结束节点连接有误')
        result = false
      }
      if (node.shape === 'activity' && !(srcrce.length === 1 && target.length === 1)) {
        node.attr('error/text', '任务节点连接有误')
        result = false
      }
      if (node.shape === 'gateway' && !(srcrce.length !== 0 && target.length !== 0)) {
        node.attr('error/text', '网关节点连接有误')
        result = false
      }
    })
    if (result) {
      this.clearValidate()
      return Promise.resolve()
    }
    return Promise.reject()
  }

  clearValidate(){
    const nodes = this.getNodes();
    nodes.forEach(node => {
      node.attr('error/text', '')
    })
  }
}